import Util from '../Util.js';
import Win from './Win.js';

// 缓存消息
const msgCache = {};
// 记录每个消息的键
let indicator = 0;
// 计时器
const timer = Util.timer();

function openWin(msg, li) {
    let index;
    for (let id in desktop.app) {
        if (desktop.app[id].name === msg.initiator.name) {
            index = id;
        }
    }
    if (index) {
        Win.open(desktop, index);
    }
    const msgId = li.getAttribute('data-notifacation-index');
    Message.delete(msgId, msgCache[msgId].msg);
    Message.deleteNotification(msgId, msgCache[msgId].notification);
    delete msgCache[msgId];
}

export default class Message {
    /**
     * 在通知中心创建消息
     * 
     * @param {Object} initiator 消息的发起者，包含icon路径
     * @param {String} content 消息内容
     * @memberof Message
     */
    constructor(initiator, content) {

        this.msgContainer = document.querySelector('#msgCtainer');
        this.systemNotificationContainer = document.querySelector('#systemNotificationContainer');
        this.initiator = initiator;
        this.content = content;

        this.buildMessage();
    }

    buildMessage() {
        const li = document.createElement('li');

        li.className = 'msg-content';
        li.setAttribute('data-notifacation-index', indicator);
        li.innerHTML = `
            <div class="exe-icon">
                <img src="${this.initiator.icon}" alt="">
            </div>
            <div class="description">
                <div class="desc">
                    ${this.content}
                </div>
            </div>
            <div class="msg-desc-ctrl notification-ctrl-${indicator}" data-notifacation-index="${indicator}">
                <i class="fa fa-times" title="清除"></i>
            </div>
        `;
        this.msgContainer.appendChild(li);

        const notification = this.buildNotification(indicator);

        // 加入缓存
        msgCache[indicator + ''] = {
            msg: li,
            notification: notification
        };

        const msgCtrls = document.querySelectorAll(`.notification-ctrl-${indicator}`);

        for (let i = 0; i < msgCtrls.length; i++) {
            msgCtrls[i].addEventListener('click', function(event) {
                const target = Util.getTarget(event, 'DIV', 'I');
                event.stopPropagation();
                const index = target.getAttribute('data-notifacation-index');

                Message.delete(index, msgCache[index].msg);
                Message.deleteNotification(index, msgCache[index].notification);
                delete msgCache[index];
            });
        }

        li.addEventListener('click', (event) => {
            event.stopPropagation();
            if (event.target.tagName !== 'I') {
                openWin(this, li);
            } 
        });

        indicator++;
        // 在新增消息时检查，以做出提示
        Message.check();
    }
    // 清除消息中心所有消息
    static clear() {
        const iter = Message.getMsgCache();

        const timer = Util.timer();
        let result;
        timer.set(() => {
            result = iter.next();
            if (!result.done) {
                Message.delete(result.value[0], result.value[1].msg);
                Message.deleteNotification(result.value[0], result.value[1].notification);
                delete msgCache[result.value[0]];
            } else {
                clearInterval(timer);
                timer.clear();
            }
        }, 300);
    }
    // 生成器获取msgCache
    static *getMsgCache() {
        for (const key in msgCache) {
            yield [key, msgCache[key]];
        }
    }
    // 删除单个消息
    static delete(index, target) {
        if (msgCache[index]) {
            // 退出样式
            target.setAttribute('style', 'left: 80%; opacity: 0;');
            setTimeout(() => {
                target.remove();
                // 在删除消息时检查，以做出提示
                Message.check();
            }, 300);
        }
    }
    static check() {

        let flag = true;

        timer.set(() => {
            if (JSON.stringify(msgCache) == "{}") {
                // 消息缓存为空时清除定时器，还原按钮
                timer.clear();
                msgCenterBtn.style.opacity = 1;
            } else {
                if (flag) {
                    msgCenterBtn.style.opacity = 0;
                    flag = false;
                } else {
                    msgCenterBtn.style.opacity = 1;
                    flag = true;
                }
            }
        }, 500);
    }

    buildNotification(id) {
        const li = document.createElement('li');
        const notification = this.systemNotificationContainer.parentElement;
        li.setAttribute('data-notifacation-index', id);
        li.innerHTML = `
            <div class="top">
                <img src="${this.initiator.icon}" alt="">
                <h2>${this.initiator.name}</h2>
                <div class="close notification-ctrl-${id}" data-notifacation-index="${id}"><i class="fa fa-times" title="清除"></i></div>
            </div>
            <div class="content">
                <p>${this.content}</p>
            </div>
        `;
        Util.animate(notification, {
            right: 0,
        }, null, 3);

        this.systemNotificationContainer.appendChild(li);

        li.addEventListener('click', (event) => {
            event.stopPropagation();
            if (event.target.tagName !== 'I') {
                openWin(this, li);
            } 
        });

        return li;
    }

    static deleteNotification(index, target) {
        if (msgCache[index]) {
            // 退出样式
            target.setAttribute('style', 'left: 80%; opacity: 0;');
            setTimeout(() => {
                target.remove();
                // 在删除消息时检查，以做出提示
                Message.check();
            }, 300);
        }
    }

}